package com.youxin.chat.pay.service.channel.impl.liantong.util;

import com.alibaba.fastjson.JSONObject;

import com.youxin.base.BaseResultCode;
import com.youxin.chat.pay.utils.RSAUtils;
import com.youxin.exception.SystemException;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.PrivateKey;
import java.security.PublicKey;

public class LianTongUtil {
    private static Logger logger = LoggerFactory.getLogger(LianTongUtil.class);

    public static String buildSign(String content, String rsaKeyPri){
        String signMsg;
        try {
            PrivateKey privateKey = RSAUtils.loadPrivateKey(rsaKeyPri);
            signMsg = Base64.encodeBase64String(RSAUtils.doSignature256((String) content, privateKey, "UTF-8"));

        } catch (Exception e) {
            logger.error("加签失败：", e);
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "加签失败");
        }
        return signMsg;
    }

    public static boolean verifySign(String rsaKeyPub, String result){
        try {
            PublicKey publicKey = RSAUtils.loadPublicKey(rsaKeyPub);
            return RSAUtils.verfy(Base64.decodeBase64(JSONObject.parseObject(result).getString("signMsg")), result.getBytes(), "SHA256withRSA", publicKey);

        } catch (Exception e) {
            logger.error("回调签名校验失败：", e);
            return false;

        }
    }
}
